//
//  GuestViewController.m
//  南京大牌档
//
//  Created by student on 13-12-25.
//  Copyright (c) 2013年 无锡第三团队. All rights reserved.
//

#import "GuestViewController.h"
#import "CollectionViewController.h"
#import "WeiboViewController.h"
#import "Reachability.h"
#import "SuggestionViewController.h"
#import "InformationViewController.h"
@interface GuestViewController ()

@end

@implementation GuestViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title=@"个人中心";
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)
    {
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.extendedLayoutIncludesOpaqueBars = NO;
        self.modalPresentationCapturesStatusBarAppearance = NO;
    }
#endif
    
    guestTV=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320, WXHLApplicationBounds().size.height-49-64) style:UITableViewStyleGrouped];
    guestTV.separatorColor=[UIColor colorWithRed:255/255.0 green:215/255.0 blue:0/255.0 alpha:1];
    guestTV.delegate=self;
    guestTV.dataSource=self;
    guestTV.backgroundColor=[UIColor whiteColor];
    mobilePhoneView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 85)];
    mobilePhoneView.backgroundColor=[UIColor whiteColor];
    mobilePhoneTF=[[UITextField alloc]initWithFrame:CGRectMake(5, 10, 310, 30)];
    mobilePhoneTF.delegate=self;
    mobilePhoneTF.borderStyle=UITextBorderStyleRoundedRect;
    mobilePhoneTF.keyboardType=UIKeyboardTypePhonePad;
    mobilePhoneTF.placeholder=@"您的手机号码:";
    [mobilePhoneView addSubview:mobilePhoneTF];
    
    UIButton *registerButton=[[UIButton alloc]initWithFrame:CGRectMake(5, 50, 150, 25)];
    [registerButton setBackgroundImage:[UIImage imageNamed:@"btn_b_unable"] forState:UIControlStateNormal];
    [registerButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [registerButton setTitle:@"注册" forState:UIControlStateNormal];
    registerButton.layer.cornerRadius=5;
    registerButton.tag=4;
    [registerButton addTarget:self action:@selector(loginOrRegisterButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [mobilePhoneView addSubview:registerButton];
    
    UIButton *loginButton=[[UIButton alloc]initWithFrame:CGRectMake(165, 50, 150, 25)];
    [loginButton setBackgroundImage:[UIImage imageNamed:@"btn_b"] forState:UIControlStateNormal];
    [loginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [loginButton setTitle:@"登录" forState:UIControlStateNormal];
    loginButton.layer.cornerRadius=5;
    loginButton.tag=5;
    [loginButton addTarget:self action:@selector(loginOrRegisterButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [mobilePhoneView addSubview:loginButton];
    
    guestTV.tableHeaderView=mobilePhoneView;

    [self.view addSubview:guestTV];
    welcomeLabel=[[UILabel alloc]initWithFrame:CGRectMake(5, 10, 310, 65)];
    welcomeLabel.backgroundColor=[UIColor whiteColor];
    welcomeLabel.textAlignment=1;
 
}

-(void)loginOrRegisterButtonPressed:(UIButton *)button
{
    [mobilePhoneTF resignFirstResponder];
//    {"success":"1","result":{"phone":"13205222628","area":"0510","postno":"214000","att":"中国,江苏,无锡","ctype":"江苏联通GSM卡","par":"1320522","prefix":"132","operators":"联通","style_simcall":"中国,江苏,无锡","style_citynm":"中华人民共和国,江苏省,无锡市"}}
    Reachability *r = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    if ([r currentReachabilityStatus]==NotReachable) {
        UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"无法注册！" message:@"请打开网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alertView show];
    }
    else{
        NSError *error;
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://api.k780.com:88/?app=phone.get&phone=%@&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json",mobilePhoneTF.text]]];
        NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
        if ((int)mobilePhoneTF.text.length!=11||[[dic objectForKey:@"success"]isEqualToString:@"0"]) {
            UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"提示" message:@"请输入正确的手机号码" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alertView show];
        }
        else{
            if (button.tag==4) {
                UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"提示" message:@"恭喜你！注册成功" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                [alertView show];
                welcomeLabel.text=[NSString stringWithFormat:@"欢迎您，来自%@的朋友！",[[dic objectForKey:@"result"] objectForKey:@"att"]];
                [mobilePhoneTF removeFromSuperview];
                [button removeFromSuperview];
                [mobilePhoneView addSubview:welcomeLabel];
            }
            else{
                welcomeLabel.text=[NSString stringWithFormat:@"欢迎您，来自%@的朋友！",[[dic objectForKey:@"result"] objectForKey:@"att"]];
                [mobilePhoneTF removeFromSuperview];
                [button removeFromSuperview];
                [mobilePhoneView addSubview:welcomeLabel];
                
            }
        }
    }

}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if([string isEqualToString:@"\n"]){
        //按回车关闭键盘
        [textField resignFirstResponder];
        return NO;
    }else if (string.length == 0){
        //判断是不是删除键
        return YES;
    }else if(textField.text.length >= 11){
        //输入的字符个数大于10，则无法继续输入，返回NO表示禁止输入
        return NO;
    }else{
        return YES;
    }
}



-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section==0) {
        return 4;
    }
    else
        return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier=@"Cell";
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell==nil) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        if (indexPath.row==0&&indexPath.section==0) {
            cell.textLabel.text=@"我的收藏";
            cell.imageView.image=[UIImage imageNamed:@"favorite_icon"];
        }
        else if (indexPath.row==1&&indexPath.section==0) {
            cell.textLabel.text=@"微博互动";
            cell.imageView.image=[UIImage imageNamed:@"icon_Hudong_xinlang"];
        }
        else if (indexPath.row==2&&indexPath.section==0) {
            cell.textLabel.text=@"扫二维码";
            cell.imageView.image=[UIImage imageNamed:@"sousuo"];
        }
        else if (indexPath.row==3&&indexPath.section==0) {
            cell.textLabel.text=@"意见反馈";
            cell.imageView.image=[UIImage imageNamed:@"cal-icon"];
        }
        else if (indexPath.row==0&&indexPath.section==1) {
            cell.textLabel.text=@"软件信息";

        }
        else if (indexPath.row==1&&indexPath.section==1) {
            cell.textLabel.text=@"清空缓存";
          
        }
        else
            cell.textLabel.text=@"检测版本";

    }
    return cell;

}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section==0) {
        return 40;
    }
    else
        return 0.1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.1;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [mobilePhoneTF resignFirstResponder];
    
    if (indexPath.row==0&&indexPath.section==0) {
        CollectionViewController *collectionVC=[[CollectionViewController alloc]init];
        
        [self.navigationController pushViewController:collectionVC animated:YES];
    }
    else if (indexPath.row==1&&indexPath.section==0){
        WeiboViewController *weiboViewVC=[[WeiboViewController alloc]init];
        [self.navigationController pushViewController:weiboViewVC animated:YES];
    }
    else if (indexPath.row==2&&indexPath.section==0){
        
    }
    else if (indexPath.row==3 &&indexPath.section==0){
        SuggestionViewController *suggestionVC=[[SuggestionViewController alloc]init];
        [self.navigationController pushViewController:suggestionVC animated:YES];
    }

    else if (indexPath.row==0 && indexPath.section ==1) {
        InformationViewController *informationVC=[[InformationViewController alloc]init];
        [self.navigationController pushViewController:informationVC animated:YES];
    }

    else if (indexPath.row ==1 && indexPath.section ==1) {
        
        UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:@"注意！" message:@"菜品、分店等数据需要重新下载" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alert1 show];
    }

    else if (indexPath.row ==2 && indexPath.section ==1) {
        activityIndicatorView=[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(145,165, 30, 30)];
        activityIndicatorView.activityIndicatorViewStyle=UIActivityIndicatorViewStyleGray;
        activityIndicatorView.tag=600;
        activityIndicatorView.hidesWhenStopped=YES;
        [activityIndicatorView startAnimating];
        [self.view addSubview:activityIndicatorView];
        
        time = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(loadTime) userInfo:nil repeats:NO];
    }

}

-(void)loadTime
{
    
    Reachability *reach=[Reachability reachabilityWithHostName:@"www.baidu.com"];;
    if ([reach currentReachabilityStatus]==NotReachable) {
        UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请检查网络是否连接" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alert1 show];
        [activityIndicatorView removeFromSuperview];
    }
    else{
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"恭喜！" message:@"当前版本为最新版本" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        [activityIndicatorView removeFromSuperview];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        
        dispatch_async(
                       dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
                       , ^{
                           NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
                           
                           NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
                           for (NSString *p in files) {
                               NSError *error;
                               NSString *path = [cachPath stringByAppendingPathComponent:p];
                               if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
                                   [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
                               }
                           }
                           [self performSelectorOnMainThread:@selector(clearCacheSuccess) withObject:nil waitUntilDone:YES];});
        
    }
}

- (void)clearCacheSuccess
{
    UIAlertView *alert2 = [[UIAlertView alloc] initWithTitle:@"缓存已清理" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
    [alert2 show];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
